package com.kaizeli.website.controller;

import com.kaizeli.website.pojo.dto.ChangePasswordDTO;
import com.kaizeli.website.pojo.dto.UserLoginDTO;
import com.kaizeli.website.pojo.dto.UserRegisterDTO;
import com.kaizeli.website.response.Result;
import com.kaizeli.website.service.UserService;
import com.kaizeli.website.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
@Tag(name = "登录功能接口", description = "用户注册、登录、Token管理")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 创建用户（管理员专用）
     */
    @PostMapping("/create")
    @SecurityRequirement(name = "Bearer Authentication")
    @Operation(summary = "创建用户（管理员专用）", description = "管理员创建用户，可创建管理员或普通用户。可绑定员工，绑定员工时只记录employee_id，用户名和密码需要手动输入")
    public Result<Map<String, Object>> createUser(@RequestBody UserRegisterDTO dto, @RequestHeader("Authorization") String authHeader) {
        log.info("接收到创建用户请求，用户类型：{}", dto.getAdministrator() == 1 ? "管理员" : "普通用户");

        try {
            // 从token中获取当前用户名
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return Result.error(401, "未登录或登录已过期");
            }
            
            String token = authHeader.substring(7);
            String currentUsername = JwtUtil.getUsernameFromToken(token);
            
            if (currentUsername == null) {
                return Result.error(401, "Token无效");
            }
            
            Map<String, Object> result = userService.createUser(dto, currentUsername);

            Boolean success = (Boolean) result.get("success");
            if (Boolean.TRUE.equals(success)) {
                return Result.success(result);
            } else {
                return Result.error(400, result.get("message").toString());
            }

        } catch (Exception e) {
            log.error("创建用户失败", e);
            return Result.error(500, "创建用户失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取员工列表（用于创建普通用户时选择）
     */
    @GetMapping("/employees")
    @SecurityRequirement(name = "Bearer Authentication")
    @Operation(summary = "获取在职员工列表", description = "获取所有在职且有身份证号的员工列表，用于创建普通用户时选择绑定")
    public Result<List<Map<String, Object>>> getEmployees() {
        try {
            List<Map<String, Object>> employees = userService.getActiveEmployees();
            return Result.success(employees);
        } catch (Exception e) {
            log.error("获取员工列表失败", e);
            return Result.error(500, "获取员工列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 修改密码
     */
    @PostMapping("/change-password")
    @SecurityRequirement(name = "Bearer Authentication")
    @Operation(summary = "修改密码", description = "用户修改自己的密码")
    public Result<Map<String, Object>> changePassword(@RequestBody ChangePasswordDTO dto, @RequestHeader("Authorization") String authHeader) {
        log.info("接收到修改密码请求");

        try {
            // 从token中获取当前用户名
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return Result.error(401, "未登录或登录已过期");
            }
            
            String token = authHeader.substring(7);
            String currentUsername = JwtUtil.getUsernameFromToken(token);
            
            if (currentUsername == null) {
                return Result.error(401, "Token无效");
            }
            
            Map<String, Object> result = userService.changePassword(dto, currentUsername);

            Boolean success = (Boolean) result.get("success");
            if (Boolean.TRUE.equals(success)) {
                return Result.success(result);
            } else {
                return Result.error(400, result.get("message").toString());
            }

        } catch (Exception e) {
            log.error("修改密码失败", e);
            return Result.error(500, "修改密码失败：" + e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录，返回JWT token，有效期3小时")
    public Result<Map<String, Object>> login(@RequestBody UserLoginDTO dto, HttpServletRequest request) {
        log.info("接收到登录请求，用户名：{}", dto.getUsername());

        try {
            Map<String, Object> result = userService.login(dto, request);

            Boolean success = (Boolean) result.get("success");
            if (Boolean.TRUE.equals(success)) {
                return Result.success(result);
            } else {
                return Result.error(401, result.get("message").toString());
            }

        } catch (Exception e) {
            log.error("用户登录失败", e);
            return Result.error(500, "登录失败：" + e.getMessage());
        }
    }

    /**
     * 验证Token
     */
    @GetMapping("/validate")
    @Operation(summary = "验证Token", description = "验证Token是否有效")
    public Result<Map<String, Object>> validateToken(@RequestHeader("Authorization") String authHeader) {
        try {
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return Result.error(401, "Token格式错误");
            }

            String token = authHeader.substring(7);
            Map<String, Object> result = userService.validateToken(token);

            Boolean success = (Boolean) result.get("success");
            if (Boolean.TRUE.equals(success)) {
                return Result.success(result);
            } else {
                return Result.error(401, result.get("message").toString());
            }

        } catch (Exception e) {
            log.error("Token验证失败", e);
            return Result.error(500, "验证失败：" + e.getMessage());
        }
    }

    /**
     * 登出
     */
    @PostMapping("/logout")
    @Operation(summary = "登出", description = "用户登出，销毁Token")
    public Result<Map<String, Object>> logout(@RequestHeader("Authorization") String authHeader) {
        try {
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return Result.error(401, "Token格式错误");
            }

            String token = authHeader.substring(7);
            Map<String, Object> result = userService.logout(token);

            Boolean success = (Boolean) result.get("success");
            if (Boolean.TRUE.equals(success)) {
                return Result.success(result);
            } else {
                return Result.error(400, result.get("message").toString());
            }

        } catch (Exception e) {
            log.error("登出失败", e);
            return Result.error(500, "登出失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除用户（管理员专用）
     */
    @DeleteMapping("/delete/{username}")
    @SecurityRequirement(name = "Bearer Authentication")
    @Operation(summary = "删除用户（管理员专用）", description = "总管理员可删除管理员和子管理员，管理员只能删除子管理员")
    public Result<Map<String, Object>> deleteUser(@PathVariable String username, @RequestHeader("Authorization") String authHeader) {
        log.info("接收到删除用户请求，目标用户：{}", username);

        try {
            // 从token中获取当前用户名
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return Result.error(401, "未登录或登录已过期");
            }
            
            String token = authHeader.substring(7);
            String currentUsername = JwtUtil.getUsernameFromToken(token);
            
            if (currentUsername == null) {
                return Result.error(401, "Token无效");
            }
            
            Map<String, Object> result = userService.deleteUser(username, currentUsername);

            Boolean success = (Boolean) result.get("success");
            if (Boolean.TRUE.equals(success)) {
                return Result.success(result);
            } else {
                return Result.error(400, result.get("message").toString());
            }

        } catch (Exception e) {
            log.error("删除用户失败", e);
            return Result.error(500, "删除用户失败：" + e.getMessage());
        }
    }
    
    /**
     * 提升子管理员为管理员（管理员及以上可用）
     */
    @PutMapping("/promote-admin/{username}")
    @SecurityRequirement(name = "Bearer Authentication")
    @Operation(summary = "提升子管理员为管理员", description = "管理员及以上可以将子管理员提升为管理员")
    public Result<Map<String, Object>> promoteToAdmin(@PathVariable String username, @RequestHeader("Authorization") String authHeader) {
        log.info("接收到提升子管理员为管理员请求，目标用户：{}", username);

        try {
            // 从token中获取当前用户名
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return Result.error(401, "未登录或登录已过期");
            }
            
            String token = authHeader.substring(7);
            String currentUsername = JwtUtil.getUsernameFromToken(token);
            
            if (currentUsername == null) {
                return Result.error(401, "Token无效");
            }
            
            Map<String, Object> result = userService.promoteToAdmin(username, currentUsername);

            Boolean success = (Boolean) result.get("success");
            if (Boolean.TRUE.equals(success)) {
                return Result.success(result);
            } else {
                return Result.error(400, result.get("message").toString());
            }

        } catch (Exception e) {
            log.error("提升用户失败", e);
            return Result.error(500, "提升用户失败：" + e.getMessage());
        }
    }
    
    /**
     * 提升管理员为总管理员（仅总管理员可用）
     */
    @PutMapping("/promote-super/{username}")
    @SecurityRequirement(name = "Bearer Authentication")
    @Operation(summary = "提升管理员为总管理员（仅总管理员可用）", description = "总管理员可以将管理员提升为总管理员")
    public Result<Map<String, Object>> promoteToSuperAdmin(@PathVariable String username, @RequestHeader("Authorization") String authHeader) {
        log.info("接收到提升管理员为总管理员请求，目标用户：{}", username);

        try {
            // 从token中获取当前用户名
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return Result.error(401, "未登录或登录已过期");
            }
            
            String token = authHeader.substring(7);
            String currentUsername = JwtUtil.getUsernameFromToken(token);
            
            if (currentUsername == null) {
                return Result.error(401, "Token无效");
            }
            
            Map<String, Object> result = userService.promoteToSuperAdmin(username, currentUsername);

            Boolean success = (Boolean) result.get("success");
            if (Boolean.TRUE.equals(success)) {
                return Result.success(result);
            } else {
                return Result.error(400, result.get("message").toString());
            }

        } catch (Exception e) {
            log.error("提升用户失败", e);
            return Result.error(500, "提升用户失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有用户列表（管理员可查看）
     */
    @GetMapping("/list")
    @SecurityRequirement(name = "Bearer Authentication")
    @Operation(summary = "获取所有用户列表", description = "管理员及以上级别可查看所有用户")
    public Result<List<Map<String, Object>>> getAllUsers() {
        try {
            List<Map<String, Object>> users = userService.getAllUsers();
            return Result.success(users);
        } catch (Exception e) {
            log.error("获取用户列表失败", e);
            return Result.error(500, "获取用户列表失败：" + e.getMessage());
        }
    }
}

